package cn.weekdragon.gscore.adapter.model.message;

import lombok.Data;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Base64;

@Data
public class Image extends Message{

    private String type = "Image";

    /**
     * 图片的imageId，群图片与好友图片格式不同。不为空时将忽略url属性
     */
    private String imageId;

    /**
     * 图片的URL，发送时可作网络图片的链接；接收时为腾讯图片服务器的链接，可用于图片下载
     */
    private String url;

    /**
     * 图片的路径，发送本地图片，路径相对于 JVM 工作路径（默认是当前路径，可通过 -Duser.dir=...指定），也可传入绝对路径。
     */
    private String path;

    /**
     * 图片的 Base64 编码
     */
    private String base64;

    public static Image fromData(byte[] imageData){
        Image image = new Image();
        image.setBase64(Base64.getEncoder().encodeToString(imageData));
        return image;
    }

    public static Image fromBufferedImage(BufferedImage bufferedImage){
        Image image = new Image();
        try(ByteArrayOutputStream bos = new ByteArrayOutputStream();) {
            ImageIO.write(bufferedImage,"png",bos);
            image.setBase64(Base64.getEncoder().encodeToString(bos.toByteArray()));
            return image;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static Image fromUrl(String url){
        Image image = new Image();
        image.setUrl(url);
        return image;
    }

    public static Image fromFile(File file){
        try {
            byte[] bytes = Files.readAllBytes(Paths.get(file.getAbsolutePath()));
            return fromData(bytes);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
